package com.gengzp.common.model.generic.resp;

import com.gengzp.common.context.TraceContextHolder;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serial;
import java.io.Serializable;

import static com.gengzp.common.constants.HttpStatusCodeConstants.FAIL;
import static com.gengzp.common.constants.HttpStatusCodeConstants.SUCCESS;

/**
 * @ClassName Result
 * @Description
 * @Author gengzp
 * @Date 2025/9/8 14:23
 */
@Data
@ApiModel(description = "统一返回结果")
public class Result<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = 2853858043879117503L;

    /**
     * 返回状态码
     */
    @ApiModelProperty(value = "返回状态码")
    private int code;

    /**
     * 返回消息
     */
    @ApiModelProperty(value = "返回消息")
    private String message;

    /**
     * 返回数据
     */
    @ApiModelProperty(value = "返回数据")
    private T data;

    /**
     * 链路追踪 traceId
     */
    @ApiModelProperty(value = "链路追踪 traceId")
    private String traceId;

    /**
     * 无参构造
     */
    private Result() {
    }

    /**
     * 构造方法私有化, 只允许通过静态方法创建实例
     */
    private Result(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.traceId = TraceContextHolder.getTraceId();
    }

    /**
     * 操作成功, 无返回数据
     */
    public static <T> Result<T> getSuccessResult() {
        return getSuccessResult(null);
    }

    /**
     * 成功返回, 返回具体数据
     *
     * @param data 返回数据
     */
    public static <T> Result<T> getSuccessResult(T data) {
        return new Result<>(SUCCESS, "操作成功", data);
    }

    /**
     * 错误返回, 指定错误消息
     *
     * @param message 错误消息
     */
    public static <T> Result<T> getFailResult(String message) {
        return getFailResult(FAIL, message);
    }

    /**
     * 错误返回, 指定错误码和错误消息
     *
     * @param code    错误码
     * @param message 错误消息
     */
    public static <T> Result<T> getFailResult(int code, String message) {
        return new Result<>(code, message, null);
    }

}
